import React, { useEffect, useState } from 'react';
import { Table, Button, Card, Modal, Form, Input, Select, Space, message, Typography, Avatar } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { AdminUser, Role } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';
import { mockAdminUsers, mockRoles } from '../../services/mockData';

const { Title } = Typography;

const AdminUserManagement: React.FC = () => {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<AdminUser | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    const savedUsers = Storage.get<AdminUser[]>(STORAGE_KEYS.ADMIN_USER + 'S') || mockAdminUsers;
    const savedRoles = Storage.get<Role[]>(STORAGE_KEYS.ROLES) || mockRoles;
    setUsers(savedUsers);
    setRoles(savedRoles);
  }, []);

  const saveUsers = (newUsers: AdminUser[]) => {
    Storage.set(STORAGE_KEYS.ADMIN_USER + 'S', newUsers);
    setUsers(newUsers);
  };

  const handleAdd = () => {
    setEditingUser(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (user: AdminUser) => {
    setEditingUser(user);
    form.setFieldsValue(user);
    setModalVisible(true);
  };

  const handleDelete = (userId: string) => {
    const newUsers = users.filter(u => u.id !== userId);
    saveUsers(newUsers);
    message.success('删除成功');
  };

  const handleSubmit = (values: any) => {
    if (editingUser) {
      // 编辑
      const newUsers = users.map(u => {
        if (u.id === editingUser.id) {
          // 仅本人可改密码，其他管理员编辑不改密码
          return values.password ? { ...editingUser, ...values } : { ...editingUser, ...values, password: u.password };
        }
        return u;
      });
      saveUsers(newUsers);
      message.success('更新成功');
    } else {
      // 新增
      const newUser: AdminUser = {
        id: Date.now().toString(),
        ...values,
        role: 'admin',
        password: values.password || 'admin123',
      };
      saveUsers([...users, newUser]);
      message.success('添加成功');
    }
    setModalVisible(false);
  };

  const currentUser = Storage.get<AdminUser>(STORAGE_KEYS.ADMIN_USER);
  const currentUserId = currentUser?.id?.toString();

  const handleEditSelf = () => {
    if (currentUser) {
      setEditingUser(currentUser);
      form.setFieldsValue(currentUser);
      setModalVisible(true);
    }
  };

  const columns = [
    {
      title: '头像',
      dataIndex: 'username',
      key: 'avatar',
      render: (username: string, record: AdminUser) => (
        <Avatar style={{ backgroundColor: '#1890ff', cursor: record.id?.toString() === currentUserId ? 'pointer' : 'default' }} onClick={() => {
          if (record.id?.toString() === currentUserId) {
            setEditingUser(record);
            form.setFieldsValue(record);
            setModalVisible(true);
          }
        }}>
          {username?.[0]?.toUpperCase() || 'A'}
        </Avatar>
      ),
      width: 60,
    },
    { title: '用户名', dataIndex: 'username', key: 'username' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    { title: '角色', dataIndex: 'roleId', key: 'roleId', render: (roleId: string) => roles.find(r => r.id === roleId)?.name || '-' },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: AdminUser) => (
        <Space size="small">
          <Button icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Button icon={<DeleteOutlined />} size="small" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Title level={2}>管理员管理</Title>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>添加管理员</Button>
      </div>
      <Card>
        <Table columns={columns} dataSource={users} rowKey="id" pagination={false} />
      </Card>
      <Modal
        title={editingUser ? (editingUser.id === currentUser?.id ? '修改我的信息' : '编辑管理员') : '添加管理员'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit} initialValues={{ roleId: roles[0]?.id }}>
          <Form.Item name="username" label="用户名" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="email" label="邮箱" rules={[{ required: true, message: '请输入邮箱' }]}>
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="password"
            label={editingUser?.id === currentUser?.id ? '新密码' : '密码'}
            rules={editingUser ? [{ min: 4, message: '密码至少4位' }] : []}
          >
            <Input.Password placeholder={editingUser ? (editingUser.id === currentUser?.id ? '如需修改请输入新密码' : '如需修改请输入新密码') : '请输入密码（默认admin123）'} />
          </Form.Item>
          {!editingUser?.id || editingUser?.id !== currentUser?.id ? (
            <Form.Item name="roleId" label="角色" rules={[{ required: true, message: '请选择角色' }]}> 
              <Select placeholder="请选择角色">
                {roles.map(role => (
                  <Select.Option key={role.id} value={role.id}>{role.name}</Select.Option>
                ))}
              </Select>
            </Form.Item>
          ) : null}
        </Form>
      </Modal>
    </div>
  );
};

export default AdminUserManagement;
